package cn.com.pansky.action.bank;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.vsame.url2sql.action.CommonAction;
import net.vsame.url2sql.sql.Model;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import cn.com.pansky.getui.AppPush;
import cn.com.pansky.payment.PayConf;
import cn.com.pansky.service.NoticeService;
import cn.com.pansky.service.OrderBackWriteService;
import cn.com.pansky.util.RequestUtils;

import com.alibaba.fastjson.JSONObject;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.psbc.payment.client.SignatureService;

/**
 * 邮储单笔查询
 * @author Administrator
 *
 */
public class PSBCAction extends CommonAction {
	
	/**
	 * 邮储支付单笔查询
	 */
	public JSONObject psbcOrderQuery(String orderNumber, String AAE051) {
		JSONObject jsonObject = new JSONObject();
		String transName = "IQSR"; // 交易名称
		// 交易数据明文数据封装开始
		String OTranAbbr = "WPER"; // 交易缩写   必填
//		String MercCode = context.getSessionVal("AAE051").toString(); // 商户号
//		String TermSsn = context.getSessionVal("orderNumberYC").toString(); // 支付时将新订单号存入session，原交易订单号 必填
		// 交易数据明文数据封装结束
		// 交易数据明文
		String Plain = "OTranAbbr="+OTranAbbr+"|MercCode="+AAE051+"|TermSsn="+orderNumber;
		
		// 交易数据明文签名
		String Signature = SignatureService.sign(Plain);
		String resultStr= "";//要返回的response信息
		HttpClient httpClient = new HttpClient();
		PostMethod postMethod = new PostMethod(PayConf.PayUrl);
		//填入各个表单域的值
		NameValuePair[] data = {
			new NameValuePair("transName", transName),
			new NameValuePair("Plain", Plain),
			new NameValuePair("Signature", Signature),
		};
		// 将表单的值放入postMethod中
		postMethod.setRequestBody(data);
		// 执行postMethod
		int statusCode = 0;
		try {
			statusCode = httpClient.executeMethod(postMethod);
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// HttpClient对于要求接受后继服务的请求，象POST和PUT等不能自动处理转发
		// 301或者302
		if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {  
			// 从头中取出转向的地址
			Header locationHeader = postMethod.getResponseHeader("location");
			@SuppressWarnings("unused")
			String location = null;
			if (locationHeader != null) {
				location = locationHeader.getValue();
			}
		} else {
			try {
				resultStr= postMethod.getResponseBodyAsString();
			} catch (IOException e) {
				e.printStackTrace();
			}
			postMethod.releaseConnection();
		}
		System.out.println("邮储单笔查询返回："+resultStr);
		if(resultStr.indexOf("<ErrorMsg>") != -1) {
			context.getDatas().put("isPass", false);
		} else {
			// 返回明文
			String plan = resultStr.substring(resultStr.indexOf("<Plain>")+7, resultStr.indexOf("</Plain>"));
			plan = plan.replace("|", ",");
			String[] array = plan.split(",");
			Map<String, String> map = new HashMap<String, String>();
			for(int i = 0; i < array.length; i++) {
				String[] keys = array[i].split("=");
				if(keys[0] != null && keys[0].equals("RespCode")) {
					map.put("RespCode", keys[1]); // 响应码
				} else if(keys[0] != null && keys[0].equals("TermSsn")) {
					map.put("TermSsn", keys[1].substring(0, keys[1].length()-7));// 订单号
				} else if(keys[0] != null && keys[0].equals("TranAmt")) {
					map.put("TranAmt", keys[1]); // 交易金额
				} else if(keys[0] != null && keys[0].equals("AcqSsn")) {
					map.put("AcqSsn", keys[1]); // 支付平台流水
				} else if(keys[0] != null && keys[0].equals("CompFlag")) {
					map.put("CompFlag", keys[1]); // 完成状态
				}
			}
			// 响应码返回00000000并且完成状态=00交易成功
			if(map.get("RespCode").equals("00000000") && map.get("CompFlag").equals("00")) {
				// 单笔查询交易成功
				jsonObject.put("bankType", "YC");
				jsonObject.put("orderNumber", map.get("TermSsn"));
				jsonObject.put("orderAmount", map.get("TranAmt"));
				jsonObject.put("qid", map.get("AcqSsn"));
				jsonObject.put("AAE010", "999999");
				jsonObject.put("state", "1");
				jsonObject.put("AAC002", "123456789");
				
			}
		}
		return jsonObject;
	}
	
	/**
	 * 支付通知页
	 */
	public void psbcPayResult() {
		NoticeService notice = new NoticeService();
		OrderBackWriteService orderBackWriteService = new OrderBackWriteService(); // 银行支付成功，系统数据回填接口
		HttpServletRequest req = context.getRequest();
		Map<String, String> reqMap = RequestUtils.getReqMap(req);
		String str = reqMap.get("Plain");
		String code = "";
		Map<String, String> map = new HashMap<String, String>();
		if(str == null || str.equals("")) {
			code = "301"; // 支付失败
		} else {
			// Plain=TranAbbr=IPER|AcqSsn=000000008448|MercDtTm=20160919155759|TermSsn=20160919155759896|
			// RespCode=00000000|TermCode=111|MercCode=1100529310001000003|TranAmt=100.00|SettDate=20141021|, EMPTEMP=TEMP, orderTime=20160919155759, showOrderamt=100.00 元
			str = str.replace("|", ",");
			String[] array = str.split(",");
			for(int i = 0; i < array.length; i++) {
				String arrStr = array[i];
				if(arrStr != null && !arrStr.equals("")) {
					String[] keys = arrStr.split("=");
					// 获取RespCode
					if(keys[0] != null && keys[0].equals("RespCode")) {
						if(keys[1] != null && keys[1].equals("00000000")) {
							// 支付成功
							// 支付成功推送消息
							TransmissionTemplate template = new TransmissionTemplate();
							APNPayload payload = new APNPayload();
							AppPush push = new AppPush();
							Model user = (Model) context.getServletSession().getAttribute("user");
							String alias = user.getString("AA001"); // 用户ID
//							String alias = "602c8a5b-5748-47cd-b4d3-6f9fa0425cdd";
							// 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
							JSONObject pushData = new JSONObject();
							pushData.put("t", "1");//业务办理类型
							pushData.put("m", "缴费通知");//通知头
							pushData.put("d", "缴费成功");//通知内容
							if(AppPush.getUserStatus(alias)) {
								template.setTransmissionContent(pushData.toString());
							}else{
								payload.addCustomMsg("t", pushData.get("t"));
								payload.addCustomMsg("m", pushData.get("m"));
								payload.addCustomMsg("d", pushData.get("d"));
								template.setAPNInfo(payload);
							}
							try {
								push.pushtoSingle(template, alias, payload);
							} catch (Exception e) {
								e.printStackTrace();
							}
							notice.add(pushData, alias);
							code = "ok";
						} else {
							code = "301"; // 支付失败
						}
						map.put("RespCode", keys[1]); // 返回码
					} 
					if(keys[0] != null && keys[0].equals("TermSsn")) {
						map.put("TermSsn", keys[1]);// 订单号
					}
					if(keys[0] != null && keys[0].equals("TranAmt")) {
						map.put("TranAmt", keys[1]); // 交易金额
					}
					if(keys[0] != null && keys[0].equals("MercDtTm")) {
						map.put("MercDtTm", keys[1]); // 商户日期时间
					}
					if(keys[0] != null && keys[0].equals("AcqSsn")) {
						map.put("AcqSsn", keys[1]); // 支付平台流水
					}
					if(keys[0] != null && keys[0].equals("账号")) {
						map.put("payNo", "999999"); // 支付账号
					}
				}
			}
		}
		try {
			map.put("bankType", "YC"); // 银行类别,YC:邮储，NH:农行，JH：建行
			map.put("CA006", context.getSessionVal("orderWriteCA006").toString());
			if(code != null && !code.equals("") && code.equals("ok")) {
				map.put("AAE010", "999999");
				orderBackWriteService.orderBackWrite(map); // 回填业务系统订单数据
			}
			context.getResponse().sendRedirect("psbcNotice.html?RespCode="+map.get("RespCode")+"&TermSsn="+map.get("TermSsn")+"&TranAmt="+map.get("TranAmt")+"&MercDtTm="+map.get("MercDtTm")+"&code="+code);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 手机支付交易
	 */
//	public void psbcPay() {
//		String transName = "WPER"; // 交易名称
//		// 交易数据明文数据封装开始
//		String TranAbbr = "WPER"; // 交易缩写   必填
//		String MercDtTm = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); // 商户日期时间 必填
//		String TermSsn = getParam("orderNumber"); //订单号 必填
//		String OSttDate = ""; // 原交易商户日期
//		String OAcqSsn = ""; // 原交易订单号
//		String MercCode = "1100529310001000003"; // 商户号 必填  测试数据：1100529310001000003
//		String TermCode = ""; // 终端号
//		String TranAmt = getParam("orderAmount"); // 交易金额 必填
//		String MercUrl = "http://"+context.getRequest().getRemoteHost()+"/bank/psbcPayResult.json?appId=6103_web&sig=xxx"; // 商户通知地址
//		String Remark1 = ""; // 备注1
//		String Remark2 = ""; // 备注2
//		String LimitTime = ""; // 有效时间
//		// 交易数据明文数据封装结束
//		// 交易数据明文
//		String Plain = "TranAbbr="+TranAbbr+"|MercDtTm="+MercDtTm+"|TermSsn="+TermSsn+"|OSttDate="
//				+OSttDate+"|OAcqSsn="+OAcqSsn+"|MercCode="+MercCode+"|TermCode="+TermCode
//				+"|TranAmt="+TranAmt+"|MercUrl="+URLEncoder.encode(MercUrl)+"|Remark1="+Remark1+"|Remark2="
//				+Remark2+"|LimitTime="+LimitTime;
//		
//		// 交易数据明文签名
//		String Signature = SignatureService.sign(Plain);
//
//		String response= "";//要返回的response信息
//        HttpClient httpClient = new HttpClient();
//        PostMethod postMethod = new PostMethod("http://103.22.255.201:8443/psbcpay/main");
//        //填入各个表单域的值
//        NameValuePair[] data = {
//          new NameValuePair("transName", transName),
//          new NameValuePair("Plain", Plain),
//          new NameValuePair("Signature", Signature),
//        };
//        // 将表单的值放入postMethod中
//        postMethod.setRequestBody(data);
//        // 执行postMethod
//        int statusCode = 0;
//        try {
//            statusCode = httpClient.executeMethod(postMethod);
//        } catch (HttpException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        // HttpClient对于要求接受后继服务的请求，象POST和PUT等不能自动处理转发
//        // 301或者302
//        if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {  
//            // 从头中取出转向的地址
//            Header locationHeader = postMethod.getResponseHeader("location");
//            String location = null;
//            if (locationHeader != null) {
//                location = locationHeader.getValue();
//            }
//        } else {
//            try {
//                response= postMethod.getResponseBodyAsString();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            postMethod.releaseConnection();
//        }
//        // 将支付页面信息返回
//        datas.put("info", response);
//	}
	
//	public static void main(String[] args) {
//		String transName = "WPER"; // 交易名称
//		// 交易数据明文数据封装开始
//		String TranAbbr = "WPER"; // 交易缩写   必填
//		String MercDtTm = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); // 商户日期时间 必填
//		String TermSsn = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()); //订单号 必填
//		String OSttDate = ""; // 原交易商户日期
//		String OAcqSsn = ""; // 原交易订单号
//		String MercCode = "1100529310001000003"; // 商户号 必填  测试数据：1100529310001000003
//		String TermCode = ""; // 终端号
//		String TranAmt = "100"; // 交易金额 必填
//		String MercUrl = "http://127.0.0.1:8080/bank/psbcPayResult.json?appId=6103_web&sig=xxx"; // 商户通知地址
//		String Remark1 = ""; // 备注1
//		String Remark2 = ""; // 备注2
//		String LimitTime = ""; // 有效时间
//		// 交易数据明文数据封装结束
//		// 交易数据明文
//		String Plain = "TranAbbr="+TranAbbr+"|MercDtTm="+MercDtTm+"|TermSsn="+TermSsn+"|OSttDate="
//				+OSttDate+"|OAcqSsn="+OAcqSsn+"|MercCode="+MercCode+"|TermCode="+TermCode
//				+"|TranAmt="+TranAmt+"|MercUrl="+URLEncoder.encode(MercUrl)+"|Remark1="+Remark1+"|Remark2="
//				+Remark2+"|LimitTime="+LimitTime;
//		
//		// 交易数据明文签名
//		String Signature = SignatureService.sign(Plain);
//
//		String response= "";//要返回的response信息
//        HttpClient httpClient = new HttpClient();
//        PostMethod postMethod = new PostMethod("http://103.22.255.201:8443/psbcpay/main");
//        //填入各个表单域的值
//        NameValuePair[] data = {
//          new NameValuePair("transName", transName),
//          new NameValuePair("Plain", Plain),
//          new NameValuePair("Signature", Signature),
//        };
//        // 将表单的值放入postMethod中
//        postMethod.setRequestBody(data);
//        // 执行postMethod
//        int statusCode = 0;
//        try {
//            statusCode = httpClient.executeMethod(postMethod);
//            if(statusCode == HttpStatus.SC_OK) {
//            	// 消息推送
////            	msgNotice();
//            }
//        } catch (HttpException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        // HttpClient对于要求接受后继服务的请求，象POST和PUT等不能自动处理转发
//        // 301或者302
//        if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {  
//            // 从头中取出转向的地址
//            Header locationHeader = postMethod.getResponseHeader("location");
//            String location = null;
//            if (locationHeader != null) {
//                location = locationHeader.getValue();
//            }
//        } else {
//            try {
//                response= postMethod.getResponseBodyAsString();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            postMethod.releaseConnection();
//        }
//        System.out.println(response);
//	}
	
	public static void main(String[] args) {
		String transName = "IQSR"; // 交易名称
		// 交易数据明文数据封装开始
		String OTranAbbr = "WPER"; // 交易缩写   必填
//		String MercCode = context.getSessionVal("AAE051").toString(); // 商户号
//		String TermSsn = context.getSessionVal("orderNumberYC").toString(); // 支付时将新订单号存入session，原交易订单号 必填
		// 交易数据明文数据封装结束
		// 交易数据明文
		String Plain = "OTranAbbr="+OTranAbbr+"|MercCode=1100529310001000360|TermSsn=491886780719649";
		
		// 交易数据明文签名
		String Signature = SignatureService.sign(Plain);
		String resultStr= "";//要返回的response信息
		HttpClient httpClient = new HttpClient();
		PostMethod postMethod = new PostMethod(PayConf.PayUrl);
		//填入各个表单域的值
		NameValuePair[] data = {
			new NameValuePair("transName", transName),
			new NameValuePair("Plain", Plain),
			new NameValuePair("Signature", Signature),
		};
		// 将表单的值放入postMethod中
		postMethod.setRequestBody(data);
		// 执行postMethod
		int statusCode = 0;
		try {
			statusCode = httpClient.executeMethod(postMethod);
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// HttpClient对于要求接受后继服务的请求，象POST和PUT等不能自动处理转发
		// 301或者302
		if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {  
			// 从头中取出转向的地址
			Header locationHeader = postMethod.getResponseHeader("location");
			@SuppressWarnings("unused")
			String location = null;
			if (locationHeader != null) {
				location = locationHeader.getValue();
			}
		} else {
			try {
				resultStr= postMethod.getResponseBodyAsString();
			} catch (IOException e) {
				e.printStackTrace();
			}
			postMethod.releaseConnection();
		}
		System.out.println("邮储单笔查询返回："+resultStr);
	}
}
